import router from './router'
import { getToken } from '@/utils/auth'
import store from './store'
import { asyncRoutes } from '@/router'

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 依据权限添加路由
function mapRoutes(asyncRoutes, firstRoutePerms, secondRoutePerms) {
  return asyncRoutes.filter(item => {
    return firstRoutePerms.includes(item.permission) && item.children.filter(item => {
      return secondRoutePerms.includes(item.permission)
    })
  })
}

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 判断是否已经获取过用户信息
      if (!store.state.user.userInfo.id) {
        const { permissions } = await store.dispatch('user/getUserInfo')
        // 判断是否是超级管理员
        if (permissions[0] === '*:*:*') {
          asyncRoutes.forEach(route => {
            router.addRoute(route)
          })
          store.commit('user/SET_ROUTES', asyncRoutes)
        } else {
          // 处理路由
          const firstRoutePerms = getFirstRoutePerms(permissions)
          const secondRoutePerms = getSecondRoutePerms(permissions)
          const filterRoutes = mapRoutes(asyncRoutes, firstRoutePerms, secondRoutePerms)
          // 添加路由
          filterRoutes.forEach(route => router.addRoute(route))
          store.commit('user/SET_ROUTES', filterRoutes)
        }
        // await store.dispatch('user/getRoutes')
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login`)
    }
  }
})
